package com.huyu.substat.modules.substat.servlet;

//import com.foresee.csi.util.EscapeUnescape;
//import com.foresee.csi.util.Util;
//import com.foresee.csi.service.bs.bxgx.business.pub.ComputeConstants;
//import com.foresee.sdsi.public_app.multiform.vo.FormEventVO;
//import com.foresee.sdsi.public_app.multiform.vo.FormResultVO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.huyu.substat.modules.substat.service.FileDownloadService;
import com.thinkgem.jeesite.common.utils.Util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class FileDownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 6873853791827384919L;
	private static Log log = LogFactory.getLog(FileDownloadServlet.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InputStream din = null;
		OutputStream rpout = null;
		try {
			String realPath = this.getServletConfig().getServletContext().getRealPath("");
			WebApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
			
			String className = Util.o2s(request.getParameter("className"));

			FileDownloadService downService = new FileDownloadService();
			Map<String, Object> rm = downService.genExcelTemplateFile(className, appContext, realPath);
			String fileName = Util.o2s(rm.get("fileName"));
			String path = Util.o2s(rm.get("path"));

			// 下载大文件
			response.reset();
			response.setHeader("Content-Disposition",
					"attachment; filename=\"" + new String(fileName.getBytes("GBK"), "ISO8859_1") + "\"");
			response.setContentType("application/octet-stream");
			int errorInt = writerMaxFile1(response, path);
			if (errorInt == 1) {
				throw new Exception("下载文件出错！");
			}

		} catch (Exception e) {
			log.debug("下载文件异常", e);
			e.printStackTrace();
			if (null == rpout) {
				response.reset();
				rpout = response.getOutputStream();
			}
			StringBuffer sb = new StringBuffer();
			sb.append("<script type='text/javascript'>alert('下载文件错误(");
			sb.append(Util.getFirstCauseMessage(e).replace('\\', '/'));
			sb.append(")');window.history.back(-1);</script>");
			rpout.write(sb.toString().getBytes());
			rpout.flush();

		} finally {
			if (null != din) {
				din.close();
				din = null;
			}
			if (null != rpout) {
				rpout.close();
				rpout = null;
			}
		}
	}

	private synchronized int writerMaxFile1(HttpServletResponse response, String pathFile) {

		byte[] buffer = new byte[4096];
		InputStream inStream = null;
		OutputStream outputStream = null;

		int errorInt = 0;

		File inFile = new File(pathFile);
		if (inFile.exists()) {
			response.setContentLength((int) inFile.length());
			try {
				// 创建流文件读入类
				inStream = new BufferedInputStream(new FileInputStream(inFile));
				outputStream = new BufferedOutputStream(response.getOutputStream());
				int n = (-1);
				while ((n = inStream.read(buffer, 0, 4096)) > -1) {
					outputStream.write(buffer, 0, n);
				}
				response.flushBuffer();
			} catch (Exception e) {
				e.printStackTrace();
				errorInt = 1;
			} finally {
				buffer = null;
				try {
					if (inStream != null) {
						inStream.close();
						inStream = null;
					}
					if (outputStream != null) {
						outputStream.close();
						outputStream = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
					errorInt = 1;
				}
			}
		} else {
			errorInt = 1;
		}

		return errorInt;
	}
}
